﻿using Entity;
using IRepository;
using IService;
using Repository;
using System.Collections.Generic;
using System.Data.Common;
using System.Threading.Tasks;
using XingWeiDaWMSProject.IRepository;

namespace Service
{
    public class WarehouseService : IWarehouseService
    {
        private readonly IWarehouseRepository _warehouseRepo;
        private readonly IOrganizationRepository _orgRepo;
        private readonly ISysOrgUserManagementRepository _userRepo;
        private readonly IStorageLocationRepository _locationRepo;

        public WarehouseService(
            IWarehouseRepository warehouseRepo,
            IOrganizationRepository orgRepo,
            ISysOrgUserManagementRepository userRepo,
            IStorageLocationRepository locationRepo)
        {
            _warehouseRepo = warehouseRepo;
            _orgRepo = orgRepo;
            _userRepo = userRepo;
            _locationRepo = locationRepo;
        }

        public async Task<List<SysOrgUserManagement>> GetWarehouseManagersAsync()
        {
            return await _userRepo.GetByRoleNameAsync("库位主管");
        }

        public async Task<List<SysOrgOrganizations>> GetAllOrganizations()
        {
            return await _orgRepo.GetAllAsync();
        }

        public async Task<PaginationResult<WarehouseEntity>> GetWarehousePageListAsync(
            string warehouseName,
            int? warehouseStatus,
            int? organizationId,
            string warehouseManager,
            PaginationQuery pagination
        )
        {
            if (pagination.PageIndex < 1) pagination.PageIndex = 1;
            if (pagination.PageSize < 1 || pagination.PageSize > 100) pagination.PageSize = 10;

            return await _warehouseRepo.GetPageListAsync(
                warehouseName, warehouseStatus, organizationId, warehouseManager, pagination
            );
        }

        public async Task AddWarehouseAsync(WarehouseAddDTO dto)
        {
            await _warehouseRepo.AddAsync(dto);
        }

        public async Task<List<SysOrgUserManagement>> GetAllUsers()
        {
            return await _userRepo.GetAllAsync();
        }
        public async Task<List<WarehouseStatusDTO>> GetWarehouseStatusListAsync()
        {
            var statusList = await _warehouseRepo.GetWarehouseStatusListAsync();
            return statusList;
        }
        public async Task DeleteWarehouseAsync(int warehouseId)
        {
            if (warehouseId <= 0)
                throw new ArgumentException("仓库ID必须大于0");

            await _warehouseRepo.DeleteAsync(warehouseId);
        }
        /// <summary>
        /// 批量更新仓库状态（包含业务校验）
        /// </summary>
        public async Task<ServiceResult> BatchUpdateStatusAsync(List<int> warehouseIds, int status)
        {
            // 1. 基础参数校验
            if (warehouseIds == null || !warehouseIds.Any())
                return new ServiceResult(false, "请选择需要操作的仓库");

            if (!new[] { 0, 1, 2 }.Contains(status)) // 只允许合法状态值
                return new ServiceResult(false, "无效的状态值（仅支持0=停用，1=启用，2=锁定）");

            // 2. 校验仓库是否存在
            var existingWarehouses = await _warehouseRepo.GetByIdsAsync(warehouseIds);
            if (existingWarehouses.Count != warehouseIds.Count)
            {
                var notFoundIds = warehouseIds.Except(existingWarehouses.Select(w => w.warehouse_id)).ToList();
                return new ServiceResult(false, $"部分仓库不存在，ID：{string.Join(',', notFoundIds)}");
            }

            // 3. 锁定前特殊校验（如果是锁定操作）
            if (status == 2)
            {
                // 3.1 检查是否已锁定
                var alreadyLocked = existingWarehouses
                    .Where(w => w.warehouse_status == "2")
                    .Select(w => w.warehouse_name)
                    .ToList();
                if (alreadyLocked.Any())
                {
                    return new ServiceResult(false, $"以下仓库已锁定：{string.Join('、', alreadyLocked)}");
                }

                // 3.2 检查是否有库存（有库存不允许锁定）
                var hasStockWarehouses = await _warehouseRepo.CheckWarehousesHasStockAsync(warehouseIds);
                if (hasStockWarehouses.Any())
                {
                    return new ServiceResult(false, $"以下仓库存在库存，不允许锁定：{string.Join('、', hasStockWarehouses)}");
                }
            }

            // 4. 执行状态更新（注意：仓库状态在数据库中是字符串类型）
            int affectedRows = await _warehouseRepo.BatchUpdateStatusAsync(warehouseIds, status.ToString());
            if (affectedRows <= 0)
                return new ServiceResult(false, "状态更新失败，未找到可操作的仓库");

            // 5. 返回成功结果
            var statusName = status switch
            {
                0 => "停用",
                1 => "启用",
                2 => "锁定",
                _ => "未知状态"
            };
            return new ServiceResult(true, $"{statusName}成功，共操作{affectedRows}个仓库");
        }
        // 实现：获取仓库详情
        public async Task<WarehouseDetailDTO> GetWarehouseDetailAsync(int warehouseId)
        {
            // 1. 参数校验
            if (warehouseId <= 0)
                throw new ArgumentException("仓库ID必须大于0", nameof(warehouseId));

            // 2. 查询仓库基本信息
            var warehouse = await _warehouseRepo.GetByIdAsync(warehouseId);
            if (warehouse == null)
                throw new KeyNotFoundException($"未找到ID为{warehouseId}的仓库（或已被删除）");

            // 3. 查询该仓库的库位数量
            int locationCount = await _warehouseRepo.GetLocationCountByWarehouseIdAsync(warehouseId);

            // 4. 查询仓库主管的联系电话（通过users_id关联用户表）
            string contactPhone = "-"; // 默认值
            if (warehouse.users_id > 0)
            {
                var manager = await _userRepo.GetByIdAsync(warehouse.users_id);
                contactPhone = manager?.PhoneNumber ?? "-"; // 若主管不存在，显示"-"
            }

            // 5. 转换为DTO（修正contact_phone的来源）
            return new WarehouseDetailDTO
            {
                warehouse_id = warehouse.warehouse_id,
                warehouse_number = warehouse.warehouse_number,
                warehouse_name = warehouse.warehouse_name,
                warehouse_capacity = warehouse.warehouse_capacity,
                warehouse_address = warehouse.warehouse_address,
                organizations_id = warehouse.organizations_id,
                users_id = warehouse.users_id,
                locationCount = locationCount,
                warehouse_status = warehouse.warehouse_status,
                create_by = warehouse.create_by ?? "-",
                create_time = warehouse.create_time,
                update_by = warehouse.update_by ?? "-",
                update_time = warehouse.update_time,
                contact_phone = contactPhone, // 这里改为仓库主管的电话
                remark = warehouse.note ?? "-"
            };
        }
        public async Task<WarehouseEditDTO> GetWarehouseForEditAsync(int id)
        {
            if (id <= 0)
                throw new ArgumentException("仓库ID必须大于0", nameof(id));

            // 1. 获取仓库基本信息
            var warehouse = await _warehouseRepo.GetByIdAsync(id);
            if (warehouse == null)
                throw new KeyNotFoundException($"未找到ID为{id}的仓库");

            // 2. 获取当前关联的库位ID（从库位表查询）
            var locationIds = await _locationRepo.GetIdsByWarehouseIdAsync(id);

            // 3. 转换为编辑DTO
            return new WarehouseEditDTO
            {
                WarehouseId = warehouse.warehouse_id,
                WarehouseNumber = warehouse.warehouse_number,
                WarehouseName = warehouse.warehouse_name,
                WarehouseCapacity = warehouse.warehouse_capacity,
                OrgId = warehouse.organizations_id,
                ManagerId = warehouse.users_id,
                Address = warehouse.warehouse_address,
                IsDefault = warehouse.default_warehouse == "true",
                Sorting = int.TryParse(warehouse.sorting, out int s) ? s : 0,
                Status = int.TryParse(warehouse.warehouse_status, out int status) ? status : 0,
                Note = warehouse.note,
                SelectedLocationIds = locationIds
            };
        }

        public async Task<ServiceResult> UpdateWarehouseAsync(WarehouseEditDTO dto)
        {
            // 1. 基础校验
            if (dto == null)
                return new ServiceResult(false, "请求参数不能为空");

            // 2. 校验仓库是否存在
            var existing = await _warehouseRepo.GetByIdAsync(dto.WarehouseId);
            if (existing == null)
                return new ServiceResult(false, $"未找到ID为{dto.WarehouseId}的仓库");

            // 3. 校验编号唯一性（排除自身）
            if (await _warehouseRepo.ExistsNumberAsync(dto.WarehouseNumber, dto.WarehouseId))
                return new ServiceResult(false, $"仓库编号「{dto.WarehouseNumber}」已存在，请更换");

            // 4. 执行更新
            try
            {
                await _warehouseRepo.UpdateWarehouseAsync(dto);
                return new ServiceResult(true, "仓库编辑成功");
            }
            catch (Exception ex)
            {
                return new ServiceResult(false, $"编辑失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 实现获取所有仓库的方法
        /// </summary>
        public async Task<List<WarehouseEntity>> GetAllAsync()
        {
            // 调用仓库层的GetAllAsync方法（假设IWarehouseRepository已定义该方法）
            return await _warehouseRepo.GetAllAsync();
        }

        public async Task<bool> TestStorageLocationConnection()
        {
            return await _warehouseRepo.TestStorageLocationConnection();
        }
        public async Task<WarehouseEntity> GetByIdAsync(int warehouseId, DbTransaction transaction)
        {
            return await _warehouseRepo.GetByIdAsync(warehouseId, transaction);
        }
    }
}